import java.util.Arrays;

public class TopKProblem {
    //找出array数组中前k小的元素
    public void solution(int[] array,int k) {
        //判断数组是否为空
        if(array == null || array.length == 0) {
            throw new RuntimeException("数组为空");
        }

        //判断k是否合法
        if(k < 0 || k > array.length) {
            throw new RuntimeException("k 不合法");
        }
        //1.用数据集合中前K个元素来建堆
        Heap heap = new Heap();
        int[] result = new int[k];
        for (int i = 0; i < result.length; i++) {
            result[i] = array[i];
        }

        heap.createHeap(result);
        //2.用剩余的N-k个元素依次与堆顶元素进行比较，不满足则替换堆顶元素
        for (int i = k; i < array.length; i++) {
            if(array[i] < result[0]) {
                result[0] = array[i];
                //调整result为大根堆
                heap.siftDown(result,0,k);
            }
        }
        Arrays.sort(result);

        System.out.println(Arrays.toString(result));
    }

}
